import { ref } from "vue";
import { defineStore } from "pinia";
import { get } from "@/utils/request";
import router from '@/router';
const modules = import.meta.glob('@/views/**/*.vue')

// 菜单折叠
export const useSysConfigStore = defineStore(
  "sysConfigStore",
  () => {
    //菜单折叠状态
    const isCollapse = ref(false);
    //tag标签
    const tags = ref([{ title: "首页", path: "/home" }]);
    //路由表
    const routerList = ref([])
    //用户信息
    const userInfo = ref({})
    //角色信息
    const roleList = ref([])
    //权限信息
    const permissionList = ref([])

    //折叠菜单栏方法
    function changeCollapse() {
      isCollapse.value = !isCollapse.value;
    }

    //添加路由
    const addRoute = async () => {
      const token = localStorage.getItem('pangu-authorization-token')
      if (!routerList.value.length) {
        //请求获取路由表数据
        if (token) {
          let res = await get('/getRoute')
          if (res && res.code === 200) {
            routerList.value = res.data
            routerList.value.forEach(item => {
              if (item.type === 'M') {
                let breadCrumbArr = [item]
                //递归查询父亲节点，用户面包屑数据组装
                const result = getBreadCrumb(item, routerList.value, breadCrumbArr)
                router.addRoute('ContainerView', {
                  path: item.path,
                  name: item.componentName,
                  meta: {
                    title: item.title,
                    icon: item.icon,
                    keepAlive: item.keepAlive,
                    breadCrumb: result
                  },
                  component: modules[`/src/views/${item.componentPath}`]
                })
              }
            })
          }
        }
      }
    }

    function getBreadCrumb(child, all, arr) {
      const result = all.find(item => item.id === child.pid)
      if (result) {
        arr.push(result)
        getBreadCrumb(result, all, arr)
      }
      return arr;
    }

    return { isCollapse, tags, routerList, userInfo, roleList, permissionList, changeCollapse, addRoute };
  },
  {
    persist: [
      {
        pick: ["isCollapse", "tags","userInfo","roleList", "permissionList"],
        storage: localStorage,
      }
    ],
  }
);
